<template>
  <div class="system-info">
    <!-- 面包屑 -->
    <div class="bread-crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>项目列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="main-middle project-box">
      <el-row :gutter="24">
        <el-col :span="16">
          <el-card class="never-card margin-b15" shadow="never">
            <div class="card-header">快捷方式</div>
            <div class="card-body">
              <ul class="card-link">
                <li>
                  <router-link to="/home/addpro">
                    <i class="fa fa-tasks" aria-hidden="true"></i>
                  </router-link>
                  <label>立项</label>
                </li>
                <li>
                  <router-link :to="{path: '/home/staffHours', query:{flag: 1}}">
                    <i class="fa fa-calendar" aria-hidden="true"></i>
                  </router-link>
                  <label>工时</label>
                </li>
                <li>
                  <router-link :to="{path: '/home/prolist/proinfo/contract', query:{flag: 1}}">
                    <i class="fa fa-file-word-o" aria-hidden="true"></i>
                  </router-link>
                  <label>合同</label>
                </li>
                <li>
                  <router-link :to="{path: '/home/prolist'}">
                    <i class="fa fa-credit-card" aria-hidden="true"></i>
                  </router-link>
                  <label>回款</label>
                </li>
                <li>
                  <router-link :to="{path: '/home/prolist/proinfo/acceptance', query:{flag: 1}}">
                    <i class="fa fa-check-square-o" aria-hidden="true"></i>
                  </router-link>
                  <label>验收</label>
                </li>
                <li>
                  <router-link :to="{path: '/home/prolist'}">
                    <i class="fa fa-print" aria-hidden="true"></i>
                  </router-link>
                  <label>报告</label>
                </li>
                <li>
                  <router-link :to="{path: '/home/prolist/proinfo/money', query:{flag: 1}}">
                    <i class="fa fa-jpy" aria-hidden="true"></i>
                  </router-link>
                  <label>费用</label>
                </li>
                <li>
                  <router-link :to="{path: '/home/prolist/proinfo/staff'}">
                    <i class="fa fa-user-o" aria-hidden="true"></i>
                  </router-link>
                  <label>成员</label>
                </li>
              </ul>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="never-card margin-b15" shadow="never">
            <div class="card-header">项目情况</div>
            <div class="card-body">
              <ul class="card-do">
                <li>
                  <router-link :to="{path: '/home/prolist'}">
                    <p>项目立项</p>
                    <span>{{proListLength}}</span>
                  </router-link>
                </li>
                <li>
                  <router-link :to="{path: '/home/prolist'}">
                    <p>项目变更</p>
                    <span>12</span>
                  </router-link>
                </li>
                <li>
                  <router-link :to="{path: '/home/prolist'}">
                    <p>项目验收</p>
                    <span>99</span>
                  </router-link>
                </li>
                <li>
                  <router-link :to="{path: '/home/prolist'}">
                    <p>项目回款</p>
                    <span>20</span>
                  </router-link>
                </li>
              </ul>
            </div>
          </el-card>
        </el-col>
        <!-- <el-col :span="8">
          <el-card class="never-card margin-b15" shadow="never">
            <div class="card-header">项目动态</div>
            <div class="card-body">项目动态</div>
          </el-card>
        </el-col> -->
      </el-row>

      <el-card class="box-card">
        <!-- 查询条件 -->
        <el-row class="table-selbox">
          <!-- 查询条件表单 -->
          <el-form :inline="true" :model="formInline" >
            <!-- 项目选择 -->
            <el-form-item label="项目名称" prop="proId">
              <el-select
                v-model="formInline.proId"
                filterable
                auto-complete="off"
                placeholder="请选择"
              >
                <el-option label="无" value></el-option>
                <el-option
                  v-for="item in proList"
                  :key="item.id"
                  :label="item.proName"
                  :value="item.id"
                  :title="item.proName"
                  style="width:650px;"
                ></el-option>
                <!-- 循环所有项目 项目名称 项目ID -->
              </el-select>
            </el-form-item>

            <!-- 客户名称 -->
            <el-form-item label="客户名称" prop="cusId">
              <el-select
                v-model="formInline.cusId"
                filterable
                auto-complete="off"
                placeholder="请选择"
              >
                <el-option label="无" value></el-option>
                <el-option
                  v-for="item in cusList"
                  :key="item.id"
                  :label="item.cusName"
                  :value="item.id"
                ></el-option>
                <!-- 循环所有客户 客户名称 客户ID -->
              </el-select>
            </el-form-item>

             <!-- 项目状态 -->
            <el-form-item label="项目状态" prop="status">
              <el-select
                v-model="formInline.status"
                auto-complete="off"
                placeholder="请选择"
              >
                <el-option label="无" value></el-option>
                <el-option label="运行中" value="1"></el-option>
                <el-option label="已完结" value="2"></el-option>
                <el-option label="中止" value="3"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button icon="el-icon-search" @click="selHandle">搜索</el-button>
            </el-form-item>
          </el-form>
        </el-row>
        <!-- 基本操作按钮 是否授权显示-->
        <el-row class="table-btns" v-if="[btnAdd,btnDel,btnUpload,btnDown].indexOf(true) > -1">
          <!-- 下载 -->
          <el-button type="success" size="medium" style="float:right;" v-if="btnDown" @click="getProExcel">
            <i class="fa fa-cloud-download" aria-hidden="true"></i> 下载
          </el-button>
        </el-row>
        <!-- 数据列表 -->
        <el-table :data="menusData" border style="width: 100%" ref="menusData" height="490">
          <!-- 全选 -->
          <!-- <el-table-column type="selection" width="40" fixed></el-table-column> -->
          <!-- 序号 -->
          <el-table-column label="序号" align="center" type="index" width="50"></el-table-column>
          <!-- 项目编号 -->
          <el-table-column :show-overflow-tooltip="true" prop="proNo" label="项目编号"></el-table-column>
          <!-- 项目名称 -->
          <el-table-column :show-overflow-tooltip="true" prop="proName" label="项目名称"></el-table-column>
          <!-- 客户名称 -->
          <el-table-column label="客户名称" :show-overflow-tooltip="true" prop="cusName" width="200"></el-table-column>
          <!-- 项目类型 -->
          <el-table-column sortable label="项目类型" width="120">
             <template slot-scope="scope">
              <span v-if="scope.row.type === 'GD'">过单项目</span>
              <span v-if="scope.row.type === 'YTR'">预投入项目</span>
              <span v-if="scope.row.type === 'ZS'">正式项目</span>
            </template>
          </el-table-column>
          <!-- 项目状态 -->
          <el-table-column label="项目状态" prop="status" width="120">
            <template slot-scope="scope">
              <span v-if="scope.row.status === 1">运行中</span>
              <span v-if="scope.row.status === 2">已完结</span>
              <span v-if="scope.row.status === 3">中止</span>
            </template>
          </el-table-column>
          <!-- 项目经理 -->
          <!-- <el-table-column sortable label="项目经理" prop="userName" width="150"></el-table-column> -->
           <!-- 项目经理 -->
          <el-table-column label="项目经理" width="150">
             <template slot-scope="scope">
              {{scope.row.mgUserName}} [{{scope.row.mgUserId}}]
            </template>
          </el-table-column>
          <!-- 操作列 -->
          <el-table-column label="管理" fixed="right" align="center" width="120">
            <template slot-scope="scope">
              <!-- 管理 -->
              <el-button size="mini" @click="editHandle(scope.row)" v-if="btnEdit"><i class="el-icon-setting"></i> 管理</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="table-pageblock">
          <!-- current-page 当前页数  page-size 每页显示数 total 总页数-->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[20,50,80,100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 按钮显示隐藏  - 默认值
      btnSel: true,
      btnDel: true,
      btnUpload: true,
      btnDown: true,
      btnAdd: true,
      btnEdit: true,

      // 列表数据
      menusData: [{}],
      // 当前页
      currentPage: 1,
      // 当前数
      pageSize: 20,
      // 总条目数
      total: 20,

      proList: [],
      cusList: [],
      userList: [],

      formInline: {
        cusId: '',
        proId: '',
        status: ''
      },
      // 本周项目数量
      proListLength: 0
    };
  },
  // 创建实例后执行
  created () {
    // 按钮级授权
    this.authorization(this.$store.state.btns);

    // 查询所有项目
    this.getProList();

    // 查询所有客户
    this.getCusList();

    // 获取所有用户
    this.getAllUser();

    // 获取分页数据
    this.getmenusDataByPage();

    // 获取一周时间
    this.getWeekStr();
  },

  // 过滤器
  filters: {
    // 客户ID显示过滤
    selCusName (value, params) {
      if (value === '0') {
        return '无';
      } else {
        for (let i = params.length; i--;) {
          if (params[i].id === value) {
            return params[i].cusName;
          }
        }
      }
    },

    // 用户ID显示过滤
    selUserName (value, params) {
      if (value === '0') {
        return '无';
      } else {
        for (let i = params.length; i--;) {
          if (params[i].userId === value) {
            return params[i].userName;
          }
        }
      }
    }
  },

  mounted () {
    // this.getHeight();
    // 增加监听事件，窗口变化时得到高度。
    // window.addEventListener('resize', this.getHeight, false);
  },
  methods: {
    // 表格高度自适应
    // getHeight () {
    // // 获取浏览器高度并计算得到表格所用高度。
    //   this.tableHeight = document.documentElement.clientHeight - 440;
    // },
    editHandle (row) {
      sessionStorage.setItem('project', JSON.stringify(row));
      this.$router.push({
        path: '/home/prolist/proinfo'
        // query: {
        //   datas: row
        // }
      });
    },

    getAllUser () {
      // findAllBaseUsers 获取所有用户
      let _this = this;
      let params = {
        status: ''
      };
      // 获取分页数据
      _this.$http.raw('api/findAllBaseUsers', params).then(res => {
        let { code, datas } = res;
        if (code === 0) {
          _this.userList = datas;
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 按钮级授权
    authorization (data) {
      let _this = this;
      for (let i in data) {
        if (data['sel'] === 0) {
          _this.btnSel = false;
        }
        if (data['add'] === 0) {
          _this.btnAdd = false;
        }
        if (data['del'] === 0) {
          _this.btnDel = false;
        }
        if (data['upload'] === 0) {
          _this.btnUpload = false;
        }
        if (data['down'] === 0) {
          _this.btnDown = false;
        }
        if (data['edit'] === 0) {
          _this.btnEdit = false;
        }
        return i;
      }
    },

    // 查询
    selHandle: function () {
      let _this = this;
      let location = _this.$store.state.userinfo.location;
      // console.log(_this.$store.state.userinfo);
      let params;
      if (location === '全部') {
        params = {
          userId: '',
          proId: _this.formInline.proId === null ? '' : _this.formInline.proId,
          cusId: _this.formInline.cusId === null ? '' : _this.formInline.cusId,
          status: _this.formInline.status === null ? '' : _this.formInline.status,
          pageNum: _this.currentPage,
          pageSize: _this.pageSize
        };
      } else {
        // 收集请求参数
        params = {
          userId: _this.$store.state.userinfo.userId,
          proId: _this.formInline.proId === null ? '' : _this.formInline.proId,
          cusId: _this.formInline.cusId === null ? '' : _this.formInline.cusId,
          status: _this.formInline.status === null ? '' : _this.formInline.status,
          pageNum: _this.currentPage,
          pageSize: _this.pageSize
        };
      }
      // 获取分页数据
      _this.$http.raw('api/findProList', params).then(res => {
        let { code, datas } = res;
        if (code === 0) {
          // 总页数
          _this.total = datas.total;
          // 数据结果集
          _this.menusData = datas.list;
          // 解决删除当前页数据后仍留在那一页 不跳回上一页的bug
          if (!datas.list.length && _this.currentPage !== 1) {
            // 当前页减一
            _this.currentPage -= 1;
            // 调用自己
            _this.getmenusDataByPage();
          }
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 刷新页面数据
    getmenusDataByPage () {
      let _this = this;

      let location = _this.$store.state.userinfo.location;
      let params;
      if (location === '全部') {
        params = {
          userId: '',
          proId: _this.formInline.proId === null ? '' : _this.formInline.proId,
          cusId: _this.formInline.cusId === null ? '' : _this.formInline.cusId,
          status: _this.formInline.status === null ? '' : _this.formInline.status,
          pageNum: _this.currentPage,
          pageSize: _this.pageSize
        };
      } else {
        // 收集请求参数
        params = {
          userId: _this.$store.state.userinfo.userId,
          proId: _this.formInline.proId === null ? '' : _this.formInline.proId,
          cusId: _this.formInline.cusId === null ? '' : _this.formInline.cusId,
          status: _this.formInline.status === null ? '' : _this.formInline.status,
          pageNum: _this.currentPage,
          pageSize: _this.pageSize
        };
      }
      _this.$http.raw('api/findProList', params).then(res => {
        let { code, datas } = res;
        // 判断Code状态
        if (code === 0) {
          // 总页数
          _this.total = datas.total;
          // 数据结果集
          _this.menusData = datas.list;
          // 解决删除当前页数据后仍留在那一页 不跳回上一页的bug
          if (!datas.list.length && _this.currentPage !== 1) {
            // 当前页减一
            _this.currentPage -= 1;
            // 调用自己
            _this.getmenusDataByPage();
          }
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 每页显示的条数改变
    handleSizeChange (val) {
      this.pageSize = val;
      // 调用刷新页面
      this.getmenusDataByPage();
    },
    // 当前页码
    handleCurrentChange (val) {
      this.currentPage = val;
      // 调用
      this.getmenusDataByPage();
    },

    // 查询所有转签项目
    getCusList () {
      let _this = this;
      _this.$http.post('/api/findAllCus').then(res => {
        let { code, datas } = res;
        if (code === 0) {
          _this.cusList = datas;
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },
    // 查询所有项目
    getProList () {
      let _this = this;
      let location = _this.$store.state.userinfo.location;
      let params;
      if (location === '全部') {
        params = {
          userId: ''
        };
      } else {
        // 收集请求参数
        params = {
          userId: _this.$store.state.userinfo.userId
        };
      }
      _this.$http.post('/api/findAllPros', params).then(res => {
        let { code, datas } = res;
        if (code === 0) {
          _this.proList = datas;
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 获取一周日期时间
    getWeekStr () {
      let _this = this;
      // 将字符串转为标准时间格式
      let date = new Date().getTime();
      let serverDate = new Date(date);
      // 周日的时间
      let sundayTime = date + ((7 - serverDate.getDay()) * 24 * 60 * 60 * 1000);
      // 周一的时间
      let mondayTime = date - ((serverDate.getDay() - 1) * 24 * 60 * 60 * 1000);
      let weekProList = [];
      _this.menusData.map(item => {
        if (new Date(item.createTime).getTime() > mondayTime && new Date(item.createTime).getTime() < sundayTime) {
          weekProList.push(item);
        }
      });
      _this.proListLength = weekProList.length;
      // console.log(_this.proListLength);
    },

    // 下载
    getProExcel () {
      let _this = this;
      let location = _this.$store.state.userinfo.location;
      // let user = _this.formInline.user === null || _this.formInline.user === undefined ? '' : _this.formInline.user;

      // 收集请求信息
      let params = {
        userId: location === '全部' ? '' : _this.$store.state.userinfo.userId,
        proId: _this.formInline.proId === null ? '' : _this.formInline.proId,
        cusId: _this.formInline.cusId === null ? '' : _this.formInline.cusId,
        status: _this.formInline.status === null ? '' : _this.formInline.status
      };

      // 根据查询下载数据
      _this.$http.download('api/downProList?userId=' + params.userId + '&proId=' + params.proId + '&cusId=' + params.cusId + '&status=' + params.status).then(res => {
        let blob = new Blob([res], {type: res.type});
        let downloadElement = document.createElement('a');
        let href = window.URL.createObjectURL(blob); // 创建下载的链接
        downloadElement.href = href;
        downloadElement.download = '项目列表.xlsx'; // 下载后文件名
        document.body.appendChild(downloadElement);
        downloadElement.click(); // 点击下载
        document.body.removeChild(downloadElement); // 下载完成移除元素
        window.URL.revokeObjectURL(href); // 释放blob对象
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    }
  }
};
</script>

<style lang='scss' scoped>
@import './index.scss';
</style>
<style lang='scss'>
.project-box {
  .el-form-item {
    margin-bottom: 4px;
  }
}
</style>
